using B.S.XZYData.Api.Wrter.Application.Command.Plan;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Plan
{
    /// <summary>
    /// 删除生产计划处理器
    /// </summary>
    public class DeletePlanHandler : IRequestHandler<DeletePlanCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<PlanModel> _planRepo;
        private readonly IBaseRepository<PlanItemModel> _planItemRepo;
        private readonly ILogger<DeletePlanHandler> _logger;

        public DeletePlanHandler(
            IBaseRepository<PlanModel> planRepo,
            IBaseRepository<PlanItemModel> planItemRepo,
            ILogger<DeletePlanHandler> logger)
        {
            _planRepo = planRepo;
            _planItemRepo = planItemRepo;
            _logger = logger;
        }

        /// <summary>
        /// 删除生产计划
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<bool>> Handle(DeletePlanCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<bool>();

            try
            {
                // 使用事务确保数据一致性
                using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);

                // 查找要删除的计划
                var planModel = _planRepo.GetAll()
                    .Where(x => x.Id == request.Id)
                    .ToList()
                    .FirstOrDefault();

                if (planModel == null)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "计划不存在";
                    return res;
                }

                // 检查是否可以删除（这里可以添加业务规则，比如已经开始生产的不能删除）
                var hasStartedItems = _planItemRepo.GetAll()
                    .Where(x => x.PlanId == request.Id && x.DoneQuantity > 0)
                    .ToList()
                    .Any();

                if (hasStartedItems)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "该生产计划已有完成数量，不能删除";
                    return res;
                }

                // 物理删除所有明细
                var planItems = _planItemRepo.GetAll()
                    .Where(x => x.PlanId == request.Id)
                    .ToList();

                foreach (var item in planItems)
                {
                    await _planItemRepo.DeleteAsync(item.Id);
                }

                // 物理删除主表
                await _planRepo.DeleteAsync(request.Id);

                scope.Complete();

                res.Data = true;
                res.Code = ApiEnum.Success;
                res.Msg = "删除成功";

                _logger.LogInformation($"用户 {request.OperateBy} 成功删除生产计划，ID: {request.Id}，单号: {planModel.Code}");
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Fail;
                res.Msg = "删除失败";
                _logger.LogError(ex, $"删除生产计划失败，ID: {request.Id}，操作人: {request.OperateBy}");
            }

            return res;
        }
    }
} 